<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Class Role
 * 园所角色管理
 */

class Role extends CT_Controller {
    function __construct()
    {
        parent::__construct();
        $this->load->model('nursery_role_model');
        $this->t = $this->ct_template;
    }


    /**
     * 角色列表
     *
     */
    public function index()
    {
        $page = $this->input->get('per_page') ? intval($this->input->get('per_page')) : 1;
        $pagesize = $this->config->item('per_page')?$this->config->item('per_page'):20;
        $start = ($page-1) * $pagesize;
        $condition = array();
        //获取总数
        $this->nursery_role_model->findAll( $condition,null,null,null,null);
        $total =$this->nursery_role_model->__numRows;
        $role_all = $this->nursery_role_model->findAll( $condition,null,null,$start,$pagesize);
        $pagelink = $this->pagination($total,$pagesize);
        $data['pagelink'] = $pagelink;
        $data['role_all'] = $role_all;
        $data['_title'] ='角色列表';
        $this->t->write('_title', '园所角色列表');
        $this->t->write('breadcrum', '园所角色列表');

        $this->t->write_view('content', 'nursery/role/index', $data, false);
        $this->t->render();
    }


    /**
     * 角色添加
     */
    function add()
    {
             //表单验证
        $this->lang->load('form_validation', 'chinese');
        $this->load->helper('form');
        $this->load->library('form_validation');
        $data = array( );
        $this->form_validation->set_rules('name', '角色名称', 'required');
        if( $this->form_validation->run() == FALSE ){

        }else{

            $name = $this->input->post('name',TRUE);
            //判断名称中是否有特殊字符
            $pattern="/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_\-]+$/u";
            if(! preg_match($pattern,$name)){
                $alerts = array('error' => '添加失败，名称存在非法字符！');
                $this->common_jump_url($alerts);
            }
            //验证角色名称是否已经存在
            $check_res=$this->nursery_role_model->check_role_name($name,NULL);
            if(!empty($check_res))
            {
                $alerts = array('error' => '添加失败，角色名称已存在');
                $this->common_jump_url($alerts);
            }
            $data = array(
                    'name'=>$name,
            );
            $this->nursery_role_model->insert($data);
            $alerts = array('success' => '角色添加成功');
            $this->common_jump_url($alerts,'/nursery/role/');

        }
        $data['_title'] ='添加角色';
        $this->t->write('_title', '园所角色添加');
        $this->t->write('breadcrum', '园所角色添加');
        $this->t->write_view('content', 'nursery/role/add', $data, false);
        $this->t->render();
    }


    /**
     * 角色编辑
     * @param $id
     */
    public  function edit()
    {
        //这个地方要用 get_post方法
        $role_id=$this->input->get_post("id",TRUE);
        if(empty($role_id)){
            $this->load->helper('url');
            redirect('/nursery/role/');
            return;
        }

        //表单验证
        $this->lang->load('form_validation', 'chinese');
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->form_validation->set_rules('name', '角色名称', 'required');

        if ( $this->form_validation->run() == FALSE ) {

        }else{
            $name = $this->input->post('name',TRUE);

            //判断名称中是否有特殊字符
            $pattern="/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_\-]+$/u";
            if(! preg_match($pattern,$name)){
                $alerts = array('error' => '修改失败，名称存在非法字符！');
                $this->common_jump_url($alerts);
            }
            //验证角色名称是否存在
            $check_res=$this->nursery_role_model->check_role_name($name,$role_id);
            if(!empty($check_res)){
                $alerts = array('error' => '修改失败，角色名称已存在');
                $this->common_jump_url($alerts);
            }
            $field = array('name'=>$name);
            $where = array('id'=>$role_id);
            $this->nursery_role_model->update($field,$where);
            $alerts = array('success' => '角色编辑成功');
            $this->common_jump_url($alerts,'/nursery/role/');



        }

        $data = array( );
        $row = $this->nursery_role_model->find( array('id'=>$role_id));
        $data['role_id']=$role_id;
        $data['name'] = $row['name'];
        $data['_title'] ='编辑角色';
        $this->t->write('_title', '园所角色编辑');
        $this->t->write('breadcrum', '园所角色编辑');
        $this->t->write_view('content', 'nursery/role/edit', $data, false);
        $this->t->render();
    }



    /**
     * 角色删除
     */

    function role_del()
    {

        $role_id=$this->input->get("id",TRUE);

        $role_res=$this->nursery_role_model->find(array('id'=>$role_id));
        if($role_res['name']==='超级管理员')
        {
            $alerts = array('error' => '参数有误，角色删除失败');
            $this->common_jump_url($alerts,'/nursery/role/');
        }
        if(!empty($role_id)){
            $where = array('id'=>$role_id);
            $this->nursery_role_model->delete($where);
            $alerts = array('success' => '角色删除成功');
            $this->common_jump_url($alerts);
        }else{
            $alerts = array('error' => '参数有误，角色删除失败');
            $this->common_jump_url($alerts,'/nursery/role/');
        }


    }



    /**
     * 为角色分配权限
     */

    public  function  set_permissions()
    {
        //获取角色id
        $role_id=$this->input->get_int("id",TRUE);
        //获取所有的权限列表
        $this->load->model("npermissions_model");
        $top_permissions_res=$this->npermissions_model->get_all_permissions();
        
        $permission_res=array();
        foreach($top_permissions_res as $key=> $val){

            $permission_res[$val]=$this->npermissions_model->get_all_permissions($key);
        }
        
        //获取已经为该角色分配的权限
        $this->load->model("nursery_role_action_model");
        $already_permission_res=$this->nursery_role_action_model->findAll(array('rid'=>$role_id));
        
        
        //默认赋值为空数组 防止新角色分配权限报错
        $already_permission_arr=array();
        foreach($already_permission_res as $val){
            $already_permission_arr[]=$val["aid"];
        }

        $role_detail=$this->nursery_role_model->find(array('id'=>$role_id));
        $data['role_name']=$role_detail['name'];

        $data['role_id'] = $role_id;
        $data['permission_res']=$permission_res;
        $data['already_permission_arr']=$already_permission_arr;

        $this->t->write('_title', '为角色分配权限');
        $this->t->write('breadcrum', '分配权限');
        $this->t->write_view('content', 'nursery/role/set', $data, false);
        $this->t->render();

    }


    public function do_add_permissions(){

        $role_id=$this->input->post("role_id",TRUE);
        $permissions=$this->input->post("permissions",TRUE);
        if(empty($permissions) || !is_array($permissions)){

            $alerts = array('error' => '请至少选择一项操作权限！');
            $this->session->set_flashdata('alerts', $alerts);
            $this->load->helper('url');
            redirect($this->referrer);
            return;
        }

        $this->load->model("nursery_role_action_model");

        //清空该角色之前已经存在权限 考虑是否需要用事务？
        $where = array('rid'=>$role_id);
        $this->nursery_role_action_model->delete($where);

        //写入权限控制表
        $multi_insert_data=$this->create_mulit_insert_data($role_id,$permissions);
        $insert_num=$this->nursery_role_action_model->mutli_insert($multi_insert_data);

        if($insert_num)
        {
            $alerts = array('success' => '角色分配权限成功');
            $this->session->set_flashdata('alerts', $alerts);
            $this->load->helper('url');
            redirect('/nursery/role/');
            return;

        }else{
            $alerts = array('error' => '数据库错误，角色分配权限失败');
            $this->session->set_flashdata('alerts', $alerts);
            $this->load->helper('url');
            redirect('/nursery/role/');
            return;
        }




    }


    /**
     * 为一条insert语句插入多条语句创建符合格式的数据
     * @param $role_id
     * @param array $arr
     * @return string
     * author wxd
     */


    private function create_mulit_insert_data($role_id,$arr=array())
    {

        $insert_str='';

        foreach($arr as $val)
        {

            $insert_str.='('.$role_id.','.$val.'),';

        }

        $insert_str=rtrim($insert_str,",");

        return $insert_str;
    }


}
